import React, { Component } from 'react'
import menus from '../admin/menuData.js'
import { Modal, Tree, message } from 'antd'
import { setPres } from '@/api/role-api.js'
import memorys from '@/utils/memoryUtils'
const { TreeNode } = Tree

export default class SetPre extends Component {
  state = {
    visible: false,
    confirmLoading: false,
    roleName: null,
    treeData: menus,
    role: {},
    checkedKeys: [],
  }

  showModal = (v) => {
    this.setState({
      visible: true,
      role: v,
      checkedKeys: v.menus,
    })
  }

  handleOk = () => {
    this.setState(
      (state) => {
        return {
          confirmLoading: true,
          role: { ...state.role, auth_name: memorys.user.username },
        }
      },
      () => {
        setPres(this.state.role).then((v) => {
          if (v.status == 0) {
            message.success('设置成功')
            this.setState({
              visible: false,
              confirmLoading: false,
            })
            this.props.getList()
          } else {
            message.error(v.msg || '设置失败')
          }
        })
      }
    )
  }

  handleCancel = () => {
    this.setState({
      visible: false,
    })
  }
  change = (e) => {
    this.setState({
      roleName: e.target.value,
    })
  }
  onExpand = (expandedKeys) => {
    console.log('onExpand', expandedKeys)
    this.setState({
      expandedKeys,
      autoExpandParent: false,
    })
  }

  onCheck = (checkedKeys) => {
    console.log('onCheck', checkedKeys)
    this.setState({ checkedKeys })
    const role = this.state.role
    role.menus = checkedKeys
    this.setState({
      role,
    })
  }

  onSelect = (selectedKeys, info) => {
    console.log('onSelect', info)
    this.setState({ selectedKeys })
  }

  renderTreeNodes = (data) =>
    data.map((item) => {
      if (item.children) {
        return (
          <TreeNode title={item.title} key={item.path} dataRef={item}>
            {this.renderTreeNodes(item.children)}
          </TreeNode>
        )
      }
      return <TreeNode key={item.path} {...item} />
    })
  render() {
    const { visible, confirmLoading, treeData } = this.state
    return (
      <Modal
        title="设置权限"
        visible={visible}
        onOk={this.handleOk}
        confirmLoading={confirmLoading}
        onCancel={this.handleCancel}
      >
        <Tree
          checkable
          onExpand={this.onExpand}
          expandedKeys={this.state.expandedKeys}
          autoExpandParent={this.state.autoExpandParent}
          onCheck={this.onCheck}
          checkedKeys={this.state.checkedKeys}
          onSelect={this.onSelect}
          selectedKeys={this.state.selectedKeys}
        >
          {this.renderTreeNodes(treeData)}
        </Tree>
      </Modal>
    )
  }
}
